package com.hc.summary.custom;



import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 非粘性 先发送数据后绑定,不接收之前数据
 * @param <T>
 */
public class NoStickLiveData<T> extends MutableLiveData<T> {
    private Map<Observer, ObserverWrap> map = new ConcurrentHashMap<>();

    @Override
    public void observe(LifecycleOwner owner, Observer<? super T> observer) {
        super.observe(owner, wrap(observer));
    }

    private Observer wrap(Observer<? super T> observer) {
        ObserverWrap observerWrap = map.get(observer);
        if (observerWrap == null) {
            observerWrap = new ObserverWrap(observer);
            map.put(observer, observerWrap);
        }
        return observerWrap;
    }

    @Override
    public void removeObserver(Observer<? super T> observer) {
        ObserverWrap observerWrap = map.remove(observer);
        if (observerWrap != null) {
            super.removeObserver(observerWrap);
        } else {
            super.removeObserver(observer);
        }
    }

    private class ObserverWrap<T> implements Observer<T> {

        private Observer target;
        private boolean ignoreOnced;

        public ObserverWrap(Observer target) {
            this.target = target;
        }

        @Override
        public void onChanged(T t) {
            if (!ignoreOnced) {
                ignoreOnced = true;
            } else {
                target.onChanged(t);
            }
        }
    }
}
